package cn.zn.modules.zzsys.cur.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.zn.framework.common.exception.RRException;
import cn.zn.framework.common.utils.FileUtils;
import cn.zn.framework.common.utils.PageUtils;
import cn.zn.framework.common.utils.Query;
import cn.zn.framework.common.vo.CodeNameVO;
import cn.zn.framework.common.vo.FinanceValues;
import cn.zn.modules.zzsys.cur.service.TSysDeptService;
import cn.zn.modules.zzsys.cur.service.TTeacherInfoService;
import cn.zn.modules.zzsys.cur.entity.TTeacherInfo;
import cn.zn.modules.zzsys.cur.entity.dto.TeacherInfoListDTO;
import cn.zn.modules.zzsys.cur.entity.dto.TempTeacherInfoDTO;
import cn.zn.modules.zzsys.enums.UserImgTypeEnum;
import cn.zn.modules.zzsys.inter.TeacherInter;
import cn.zn.modules.zzsys.inter.vo.TeacherInfoVO;
import cn.zn.modules.zzsys.cur.mapper.TTeacherInfoMapper;
import cn.zn.modules.zzsys.cur.service.TSysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TTeacherInfoServiceImpl extends ServiceImpl<TTeacherInfoMapper, TTeacherInfo>
        implements TTeacherInfoService, TeacherInter {

    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private FinanceValues financeValues;
    @Autowired
    private TSysDeptService tSysDeptService;
    @Autowired
    private TSysUserService tSysUserService;
    private HanyuPinyinOutputFormat outputForm = new HanyuPinyinOutputFormat();

    {
        outputForm.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        outputForm.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    @Override
    @Deprecated
    public PageUtils queryPage(Map<String, Object> params) {
        String search = (String) params.get("search");

        IPage<TTeacherInfo> iPage = new Query<TTeacherInfo>().getPage(params);
        List<TTeacherInfo> list = baseMapper.queryPage(search, iPage);
        iPage.setRecords(list);

        return new PageUtils(iPage);
    }

    @Override
    public List<TeacherInfoVO> queryByRole(String roleId, List<String> unUserCode) {
        return this.baseMapper.queryByRoleId(roleId, unUserCode).stream().map(o -> {
            TeacherInfoVO vo = new TeacherInfoVO(financeValues);
            BeanUtils.copyProperties(o, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public TeacherInfoVO findByWorkNo(String workNo) {
        TeacherInfoVO teacherInfoVO = new TeacherInfoVO(financeValues);
        TTeacherInfo teacherInfo = this.getOne(new QueryWrapper<TTeacherInfo>().eq("WORK_NO_", workNo));
        BeanUtils.copyProperties(teacherInfo, teacherInfoVO);
        if (StrUtil.isNotBlank(teacherInfoVO.getSignImgPath())) {
            teacherInfoVO.setSignImgPath(fileUtils.getDomainUrl(teacherInfoVO.getSignImgPath()));
        }
        if (StrUtil.isNotBlank(teacherInfoVO.getConfirmImgPath())) {
            teacherInfoVO.setConfirmImgPath(fileUtils.getDomainUrl(teacherInfoVO.getConfirmImgPath()));
        }
        return teacherInfoVO;
    }

    @Override
    public Map<String, TeacherInfoVO> findByWorkNos(List<String> workNos) {
        if (workNos == null || workNos.isEmpty()) {
            return Maps.newHashMap();
        }
        return super.list(new QueryWrapper<TTeacherInfo>().in("WORK_NO_", workNos)).stream()
                .collect(Collectors.toMap(
                        TTeacherInfo::getWorkNo,
                        o -> {
                            TeacherInfoVO vo = new TeacherInfoVO(financeValues);
                            vo.setName(o.getName());
                            vo.setNamePy(o.getNamePy());
                            vo.setWorkNo(o.getWorkNo());
                            return vo;
                        },
                        (o1, o2) -> o2));
    }

    @Override
    public PageUtils queryPage(TeacherInfoListDTO dto) {
        IPage<TTeacherInfo> page = super.page(dto.getPage(), dto.getWrapper());
        List<TeacherInfoVO> vos = page.getRecords().stream().map(o -> {
            TeacherInfoVO vo = new TeacherInfoVO(financeValues);
            BeanUtils.copyProperties(o, vo);
            return vo;
        }).collect(Collectors.toList());
        return new PageUtils(vos, Long.valueOf(page.getTotal()).intValue(), Long.valueOf(page.getSize()).intValue(), Long.valueOf(page.getCurrent()).intValue());
    }

    @Override
    public List<TTeacherInfo> queryByRole(String roleCode) {
        return this.baseMapper.queryByRole(roleCode);
    }

    @Override
    public List<TTeacherInfo> queryNoWork(String roleCode, String apoinDate) {
        return this.baseMapper.queryNoWork(roleCode, apoinDate);
    }

    @Override
    public String saveImgs(UserImgTypeEnum userImgType, String id, MultipartFile multipartFile) {
        try {
            String fileName = multipartFile.getOriginalFilename();
            File outputFile = fileUtils.updateFile(multipartFile.getInputStream(), fileName.substring(fileName.lastIndexOf(".") + 1), false, "zSign", id);
            String path = fileUtils.getNoBasePath(outputFile.getPath()).replace(File.separator, "/");
            super.update(new UpdateWrapper<TTeacherInfo>().eq("ID_", id)
                    .set(userImgType.equals(UserImgTypeEnum.SIGN), "SIGN_IMG_PATH_", path)
                    .set(userImgType.equals(UserImgTypeEnum.AGREE), "CONFIRM_IMG_PATH_", path)
            );
            return fileUtils.getDomainUrl(path);
        } catch (IOException e) {
            log.error("", e);
            throw new RRException("");
        }
    }

    @Override
    public void importDetail(MultipartFile file) {
        try {
            // 从EXCEL中获取数据
            @Cleanup InputStream io = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(io, 0, true);
            List<List<Object>> list = reader.read(1);
            List<TempTeacherInfoDTO> tempTeacherInfoDTOS = Lists.newArrayList();
            // 查询所有部门及项目
            Map<String, String> deptMap = tSysDeptService.deptAll("").stream().collect(Collectors.toMap(CodeNameVO::getName, CodeNameVO::getCode, (v1, v2) -> v1));
            list.forEach(objects -> {
                tempTeacherInfoDTOS.add(TempTeacherInfoDTO.builder()
                        .workNo(objects.get(0) != null ? String.valueOf(objects.get(0)).trim() : null)
                        .wageNo(objects.get(1) != null ? String.valueOf(objects.get(1)).trim() : null)
                        .realName(objects.get(2) != null ? String.valueOf(objects.get(2)).trim() : null)
                        .idNo(objects.get(3) != null ? String.valueOf(objects.get(3)).trim() : null)
                        .deptId(objects.get(4) != null ? deptMap.get(String.valueOf(objects.get(4))).trim() : null)
                        .deptName(objects.get(4) != null ? String.valueOf(objects.get(4)).trim() : null)
                        .build());
            });
            this.baseMapper.createTempTeacherImport();
            this.baseMapper.insertTempTeacherImport(tempTeacherInfoDTOS);
        } catch (IOException e) {
            throw new RRException("读取文件内容时出错");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAll() {
        this.baseMapper.selectTempTeacherImport().forEach(o -> {
            TTeacherInfo tTeacherInfo = new TTeacherInfo();
            BeanUtils.copyProperties(o, tTeacherInfo);
            tTeacherInfo.setAuditPwd(DigestUtils.md5DigestAsHex("111111".getBytes()));
            tTeacherInfo.setName(o.getRealName());
            try {
                tTeacherInfo.setNamePy(PinyinHelper.toHanYuPinyinString(tTeacherInfo.getName(), outputForm, "", false));
            } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                log.error("姓名转拼音：{},失败：{}", tTeacherInfo.getName(), badHanyuPinyinOutputFormatCombination.getMessage());
            }
            if (tTeacherInfo.getIdNo() == null) {
                tTeacherInfo.setIdNo("410");
            }
            super.save(tTeacherInfo);
            tSysUserService.saveForReg(o.getWorkNo(), "888888", o.getRealName(), "", "", null, tTeacherInfo.getId(), o.getDeptId());

        });
    }

    @Override
    public void buildSign() {
        Map<String, TTeacherInfo> teacherInfoMap = super.list().stream().collect(Collectors.toMap(TTeacherInfo::getName, o -> o, (o1, o2) -> o1));
        String dirPath = "";
        String targetDirPath = "";
        String relativePath = "";
        FileUtil.del(targetDirPath);
        File[] files = FileUtil.ls(dirPath);
        Lists.newArrayList(files).forEach(o -> {
            if (o.isDirectory() && teacherInfoMap.containsKey(o.getName())) {
                TTeacherInfo tTeacherInfo = teacherInfoMap.get(o.getName());
                log.debug("文件夹:{},工号:{}", o.getName(), tTeacherInfo.getWorkNo());
                String dirName = targetDirPath.concat(File.separator).concat(tTeacherInfo.getWorkNo());
                FileUtil.mkdir(dirName);
                File[] subFiles = FileUtil.ls(o.getPath());
                TTeacherInfo saveEntity = new TTeacherInfo();
                Lists.newArrayList(subFiles).forEach(file -> {
                    String suffix = file.getName().substring(file.getName().lastIndexOf("."));
                    String fileName = "";
                    if (file.getName().indexOf("同意") == -1) {
                        fileName = tTeacherInfo.getWorkNo().concat("_sign_80x80".concat(suffix));
                        saveEntity.setSignImgPath(relativePath.concat("/").concat(tTeacherInfo.getWorkNo()).concat("/").concat(fileName));
                    } else {
                        fileName = tTeacherInfo.getWorkNo().concat("_confirm_80x80".concat(suffix));
                        saveEntity.setConfirmImgPath(relativePath.concat("/").concat(tTeacherInfo.getWorkNo()).concat("/").concat(fileName));
                    }
                    String filePath = targetDirPath.concat(File.separator).concat(tTeacherInfo.getWorkNo()).concat(File.separator).concat(fileName);
                    log.debug(filePath);
                    FileUtil.copy(file, new File(filePath), true);
                });
                log.debug("saveEntity:{},{}", saveEntity.getSignImgPath(), saveEntity.getConfirmImgPath());
                super.update(saveEntity, new QueryWrapper<TTeacherInfo>().eq("ID_", tTeacherInfo.getId()));
            }
        });
    }
}
